﻿using Domain.Entities.Tenants;
using System.Linq.Dynamic.Core;

namespace Infrastructure.Repositories;

#nullable disable

public class MultiTenancyRepository : IMultiTenantRepository
{
    private readonly IApplicationDbContext _context;

    public MultiTenancyRepository(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<bool> AddOrEditAsync(Tenant tenant)
    {
        var tenantToAddOrEdit = await _context.Tenants.FirstOrDefaultAsync(x => x.Id == tenant.Id);
        if (tenantToAddOrEdit == null) 
        {
          await  _context.Tenants.AddAsync(tenant);
        }
        else 
        {
            _context.Tenants.Update(tenant);
        }
        return await _context.SaveChangesAsync() > 0;
    }

    public async Task<List<Tenant>> GetAllAsync()
    {      
         var tenants = await _context.Tenants.AsNoTracking().ToListAsync();
         return tenants;
    }

    public async Task<List<Tenant>> GetAllEnabledAsync()
    {
        return (await GetAllAsync()).Where(x => x.Enabled == true).ToList();
    }

    public Tenant GetDefault()
    {
        return _context.Tenants.FirstOrDefault(x => x.Enabled == true && x.IsDefault);
    }
}
